package cn.jhz.filesharingsystem.web;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import cn.jhz.filesharingsystem.model.User;


public class MyWebSocketHandler implements WebSocketHandler{


    private static final Logger log = Logger.getLogger(MyWebSocketHandler.class);

    // 保存所有的用户session
    private static final Map<String,WebSocketSession> userList = new ConcurrentHashMap<String,WebSocketSession>();
    
    private static final ConcurrentHashMap<String,Map<String,WebSocketSession>> chatRooms = new ConcurrentHashMap<>();
    // 连接 就绪时 
    @Override
    public void afterConnectionEstablished(WebSocketSession session)
            throws Exception {

        log.info("connect websocket success.......");
        userList.put(((User)(session.getAttributes().get("loginUser"))).getEmail(), session);
        
        for (String room : chatRooms.keySet()) {
        	session.sendMessage(new TextMessage("{\"pid\":\""+0+"\",\"msgContent\":\""+room+"\"}",true));
		}
        
    }


    /*处理信息*/
    @Override
    public void handleMessage(WebSocketSession session,
            WebSocketMessage<?> message) throws Exception {

        Gson gson = new Gson();
        User user = (User) session.getAttributes().get("loginUser");
        String room;
        
        // 将消息JSON格式通过Gson转换成Map
        // message.getPayload().toString() 获取消息具体内容
        Map<String, Object> msg = gson.fromJson(message.getPayload().toString(), 
                new TypeToken<Map<String, Object>>() {}.getType());
 
        log.info("handleMessage......."+message.getPayload()+"..........."+msg);
        // 处理消息 msgContent消息内容
        TextMessage textMessage;
       switch ((String)msg.get("pid")) {
		case "0":
			/*房间的创建和加入*/
			room = (String) session.getAttributes().get("room");
			/* 判断用户是否已加入其他房间,如果是则自动退出 */
			if(room != null && room != msg.get("msgContent")) {
				chatRooms.get(room).remove(user.getEmail());
			}
			/* 判断房间是否已经存在,若不存在则创建然后进入,若存在则直接进入*/
			if(room != msg.get("msgContent")) {
				if(chatRooms.get(msg.get("msgContent"))==null) {
					chatRooms.put((String) msg.get("msgContent"), new ConcurrentHashMap<String, WebSocketSession>());
					textMessage = new TextMessage("{\"pid\":\""+0+"\",\"msgContent\":\""+msg.get("msgContent")+"\"}",true);
					sendNoteToAllUsers(textMessage);
				}
				session.getAttributes().put("room", msg.get("msgContent"));
				chatRooms.get(msg.get("msgContent")).put(user.getEmail(), session);
			}
			
			break;
		case "1":
			/* 用户短信的转发 */
			textMessage = new TextMessage("{\"pid\":\""+1+"\",\"timeStamp\":\""+new Date()+"\",\"source\":\""+((User)(session.getAttributes().get("loginUser"))).getUsername()+"\",\"msgContent\":\""+Pattern.compile("\n").matcher(msg.get("msgContent").toString()).replaceAll("\\\\n").trim()+"\"}", true);
	        /* 根据用户所属房间,进行短信转发 */
			if((room = (String) session.getAttributes().get("room"))!=null)
				sendMsgToAllUsers(textMessage, room);
			//调用方法(发送消息给所有人)
			break;
		default:
			break;
       }
    }


    // 处理传输时异常
    @Override
    public void handleTransportError(WebSocketSession session,
            Throwable exception) throws Exception {
        // TODO Auto-generated method stub

    }



    // 关闭 连接时
    @Override
    public void afterConnectionClosed(WebSocketSession session,
            CloseStatus closeStatus) throws Exception {

        log.info("connect websocket closed.......");
        
        String email = ((User)(session.getAttributes().get("loginUser"))).getEmail();
        userList.remove(email);
        for (@SuppressWarnings("rawtypes") Map room:chatRooms.values()) {
			if(room.remove(email)!=null)
				break;
		}

    }



    @Override
    public boolean supportsPartialMessages() {
        // TODO Auto-generated method stub
        return false;
    }



    // 给所有用户发送 信息
    public void sendMsgToAllUsers(WebSocketMessage<?> message, String room) throws Exception{

        for (WebSocketSession user : chatRooms.get(room).values()) {
            user.sendMessage(message);
        }

    }
    // 给所有用户发送 信息
    public void sendNoteToAllUsers(WebSocketMessage<?> message) throws Exception{

        for (WebSocketSession user : userList.values()) {
            user.sendMessage(message);
        }

    }
}
